package com.yinhai.service;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.StyleSpan;

import com.yinhai.activity.R;
import com.yinhai.cfg.LoginConfig;
import com.yinhai.cfg.LoginConfigUtil;
import com.yinhai.constant.Contact;
import com.yinhai.dao.IMDaoImpl;
import com.yinhai.dao.MsgDaoImpl;
import com.yinhai.model.ChatMsgEntity;
import com.yinhai.model.IMList;
import com.yinhai.model.MsgModel;
import com.yinhai.util.GetTimeLength;
import com.yinhai.util.NullUtils;

/**
 * 短信操作类
 * 
 * @author Administrator
 *
 */
public class MsgServiceImpl {
    private MsgDaoImpl msgDao;
    
    private SpannableString spannablepic;
    
    private Context context;
    
    private IMDaoImpl imDaoImpl;
    
    public MsgServiceImpl(Context context) {
        msgDao = new MsgDaoImpl(context);
        imDaoImpl = new IMDaoImpl(context);
        this.context = context;
    }
    
    public void insert(MsgModel entity) {
        msgDao.insert(entity);
    }
    
    /**
     * 查询即时聊天列表数据
     * 
     * @param sendID 发送人
     * @param receID 接收人
     */
    public List<IMList> findByMsgList(String sendID, String receID) {
        return imDaoImpl.rawQuery("select * from im_list where send_user_id=? and rec_id=?", new String[] {sendID,
            receID});
    }
    
    public List<IMList> findOwnMsgList() {
        LoginConfig config = LoginConfigUtil.getConfig(context);
        return imDaoImpl.rawQuery("select * from im_list where  show_status = '1' and  send_user_id=? ",
            new String[] {config.getUsername()});
    }
    
    public List<IMList> findOwnMsgListNew() {
        LoginConfig config = LoginConfigUtil.getConfig(context);
        return imDaoImpl.rawQuery("select * from im_list where send_user_id=? or rec_id=?",
            new String[] {config.getUsername(), config.getUsername()});
    }
    
    public void saveIM(MsgModel entity) {
        LoginConfig loginConfig = LoginConfigUtil.getConfig(context);
        List<IMList> imLists = null;
        // im_list表存储的发送者都是当前登录帐号
        String sendID = null, sendName = null, receID = null, receName = null;
        if (entity.getSendUserId().equals(loginConfig.getUsername())) {
            sendID = entity.getSendUserId();
            sendName = entity.getSendUserName();
            // 如果是群组存储群组ID
            receID = entity.getIsGroup().equals("0") ? entity.getRecId() : entity.getGroupId();
            receName = entity.getIsGroup().equals("0") ? entity.getRecName() : entity.getGroupName();
            imLists = findByMsgList(entity.getSendUserId(), entity.getRecId());
        } else {
            sendID = entity.getIsGroup().equals("0") ? entity.getRecId() : loginConfig.getUsername();
            sendName = entity.getIsGroup().equals("0") ? entity.getRecName() : "";
            receID = entity.getIsGroup().equals("0") ? entity.getSendUserId() : entity.getGroupId();
            receName = entity.getIsGroup().equals("0") ? entity.getSendUserName() : entity.getGroupName();
            // imLists = findByMsgList(entity.getRecId(),
            // entity.getSendUserId());
            imLists = findByMsgList(sendID, receID);
        }
        IMList imList = null;
        
        if (imLists != null && !imLists.isEmpty()) {
            imList = imLists.get(0);
        } else {
            imList = new IMList();
            imList.setSendUserName(sendName);
            imList.setSendUserId(sendID);
            imList.setRecId(receID);
            imList.setRecName(receName);
        }
        imList.setSendDate(entity.getSendDate());
        imList.setIsGroup(entity.getIsGroup());
        imList.setShowStatus("1");
        if (Contact.TEXT == Integer.valueOf(entity.getConType())) {
            imList.setContent(entity.getContent());
        } else if (Contact.PHOTO == Integer.valueOf(entity.getConType())) {
            imList.setContent("[图片]");
        } else if (Contact.REDIO == Integer.valueOf(entity.getConType())) {
            imList.setContent("[语音]");
        } else if (Contact.POSMAP == Integer.valueOf(entity.getConType())) {
            imList.setContent("[位置]");
        }
        // 如果是别人发的未读条数加1
        if (!entity.getSendUserId().equals(loginConfig.getUsername())) {
            imList.setUnreadNumber(imList.getUnreadNumber() + 1);
        }
        
        if (imList.getId() > 0) {
            imDaoImpl.update(imList);
        } else {
            long id = imDaoImpl.insert(imList);
            imList.setId(Integer.valueOf(id + ""));
        }
        
        entity.setParent_id(imList.getId());
        
        msgDao.insert(entity);
    }//
     // msg_model
    
    public void Update_Id(String isreceipt, String id) {
        String sql = "update msg_model set isreceipt='" + isreceipt + "' where uuid='" + id + "'";
        msgDao.execSql(sql, null);
    }
    
    public void updateReceipt(String isReceipt, String guid) {
        // findByMsgList(sendID, receID)
        String sql = "update msg_model set isreceipt=? where guid<?";
        msgDao.execSql(sql, new String[] {isReceipt, guid});
    }
    
    public void updateReceipt(String isReceipt, String guid, String sendID, String receID) {
        List<IMList> imLists = findByMsgList(sendID, receID);
        if (NullUtils.isNotEmpty(imLists)) {
//            String sql = "update msg_model set isreceipt=? where guid=? and parent_id=?";
//            msgDao.execSql(sql, new String[] {isReceipt, guid, imLists.get(0).getId() + ""});
            String sql = "update msg_model set isreceipt=? where uuid=?";
            msgDao.execSql(sql, new String[] {isReceipt, guid});
        }
        
    }
    
    public void updateMessage(String content, String guid, String uuid) {
        String sql = "update msg_model set fileName=?,guid=?,status=2 where uuid=?";
        msgDao.execSql(sql, new String[] {content, guid, uuid});
    }
    
    public void updateStatus(String status, String uuid) {
        String sql = "update msg_model set status=? where uuid=?";
        msgDao.execSql(sql, new String[] {status, uuid});
    }
    
    public MsgModel findByGuid(String guid) {
        List<MsgModel> models = msgDao.rawQuery("select * from msg_model where uuid='"+guid+"'", null);
        if (NullUtils.isNotEmpty(models)) {
            return models.get(0);
        }
        return null;
    }
    
    // 通过ID更新im_list表状态
    public void updateShowStatusByIM_Id(String id) {
        String sql = "update im_list set show_status='0' where id=" + Integer.parseInt(id);
        imDaoImpl.execSql(sql, null);
    }
    
    // 通过groupID更新im_list表状态
    public void updateShowStatusByIM_GroupId(String groupid) {
        String sql = "update im_list set show_status='0' where group_id=" + groupid;
        imDaoImpl.execSql(sql, null);
    }
    
    // 通过senderId receiverId更新im_list表
    public void updateShowContentP2P(MsgModel msgModel, String content) {
        String sql =
            "update im_list set content='" + content + "',send_date='" + msgModel.getSendDate() + "' where id="
                + msgModel.getParent_id();
        
        imDaoImpl.execSql(sql, null);
    }
    
    // 通过senderId groupId更新im_list表
    public void updateShowContentGroup(MsgModel msgModel, String content) {
        String sql =
            "update im_list set content='" + content + "',send_date='" + msgModel.getSendDate() + "' where id="
                + msgModel.getParent_id();
        imDaoImpl.execSql(sql, null);
    }
    
    // 清空im_list表根据senderId receiverId删除
    public void delIMListByP2P(MsgModel msgModel) {
        String sql = "delete from im_list where id=" + msgModel.getParent_id();
        imDaoImpl.execSql(sql, null);
    }
    
    // 清空im_list表根据senderId groupId删除
    public void delIMListByGroup(String sendID, String receID) {
        String sql = "delete from im_list where send_user_id=? and rec_id=? ";
        imDaoImpl.execSql(sql, new String[] {sendID, receID});
    }
    
    // 清空im_list表
    public void clearIM() {
        String sql = "delete from im_list";
        imDaoImpl.execSql(sql, null);
    }
    
    // 清空msg_model表
    public void clearMsgModel() {
        String sql = "delete from msg_model";
        msgDao.execSql(sql, null);
    }
    
    public void clearIMNumbers(String currentId, String otherId) {
        List<IMList> imLists = findByMsgList(currentId, otherId);
        
        if (imLists.isEmpty()) {
            return;
        }
        IMList imList = imLists.get(0);
        imList.setUnreadNumber(0);
        imDaoImpl.update(imList);
    }
    
    /**
     * 根据单个人的聊天用户唯一标识获取与当前对话用户有关的聊天消息 历史消息获取
     * 
     * @param id currentId 自己的唯一标识 otherId其他人的唯一标识,当是群组聊天时候otherId为群组ID
     * @return
     */
    public List<ChatMsgEntity> findSimgleMessage(String currentId, String otherId, boolean isGroup) {
        List<MsgModel> msgModels = null;
        // if (isGroup) {
        // String sql =
        // "select m.* from msg_model m where (m.rec_id=? or m.send_user_id=?) and group_id=? order by send_date asc";
        // msgModels = msgDao.rawQuery(sql, new String[] { currentId,
        // currentId, otherId });
        // } else {
        // String sql =
        // "select m.* from msg_model m where ((m.rec_id=? and m.send_user_id=?) or (m.send_user_id=? or m.rec_id=?)) and is_group = ? order by send_date asc";
        // msgModels = msgDao.rawQuery(sql, new String[] { currentId, otherId,
        // currentId, otherId, "0" });
        // }
        List<IMList> imLists = findByMsgList(currentId, otherId);
        
        if (imLists.isEmpty()) {
            return new ArrayList<ChatMsgEntity>();
        }
        IMList imList = imLists.get(0);
        imList.setUnreadNumber(0);
        imDaoImpl.update(imList);
        String sql = "select * from msg_model where parent_id=?  order by id desc  limit 20";
        
        msgModels = msgDao.rawQuery(sql, new String[] {imList.getId() + ""});
        
        List<ChatMsgEntity> chatMsgs = new ArrayList<ChatMsgEntity>();
        if (msgModels != null) {
            ChatMsgEntity chatMsg = null;
            for (int i = msgModels.size() - 1; i >= 0; i--) {
                MsgModel msgModel = msgModels.get(i);
                chatMsg = new ChatMsgEntity();
                chatMsg.setMsgModel(msgModel);
                chatMsg.setId(msgModel.getId());
                chatMsg.setDate(msgModel.getSendDate());
                chatMsg.setName(msgModel.getSendUserName());
                chatMsg.setSendUserId(msgModel.getSendUserId());
                chatMsg.setRecId(msgModel.getRecId());
                chatMsg.setUuid(msgModel.getUuid());
                chatMsg.setIsreceipt(msgModel.getIsreceipt());
                
                if (currentId.equals(msgModel.getSendUserId())) {
                    // 发送者是自己
                    chatMsg.setComMeg(false);
                } else {
                    chatMsg.setComMeg(true);
                }
                chatMsg.setType(msgModel.getConType());
                // 判断发送的类型
                if (Contact.TEXT == Integer.valueOf(msgModel.getConType())) {
                    // 文字内容
                    chatMsg.setText(msgModel.getContent());
                } else if (Contact.PHOTO == Integer.valueOf(msgModel.getConType())) {
                    chatMsg.setText(msgModel.getContent());
                    chatMsg.setFileName(msgModel.getFileName());
                } else if (Contact.REDIO == Integer.valueOf(msgModel.getConType())) {
                    // 声音
                    chatMsg.setFileName(msgModel.getFileName());
                    chatMsg.setText("");
                    Bitmap bitmap = null;
                    if (currentId.equals(msgModel.getSendUserId())) {
                        Drawable d = context.getResources().getDrawable(R.drawable.me_dis_read);
                        ; // xxx根据自己的情况获取drawable
                        BitmapDrawable bd = (BitmapDrawable)d;
                        bitmap = bd.getBitmap();
                        ImageSpan imageSpan = new ImageSpan(context, bitmap);
                        String yy_str = "a  " + GetTimeLength.getTimeLength(msgModel.getSecond());
                        spannablepic = new SpannableString(yy_str);
                        spannablepic.setSpan(new ForegroundColorSpan(Color.LTGRAY),
                            3,
                            yy_str.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        spannablepic.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC),
                            3,
                            yy_str.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        spannablepic.setSpan(imageSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        chatMsg.setSpStr(spannablepic);
                    } else {
                        Drawable d = context.getResources().getDrawable(R.drawable.other_dis_read); // xxx根据自己的情况获取drawable
                        BitmapDrawable bd = (BitmapDrawable)d;
                        bitmap = bd.getBitmap();
                        ImageSpan imageSpan = new ImageSpan(context, bitmap);
                        String yy_str = "a  " + GetTimeLength.getTimeLength(msgModel.getSecond());
                        spannablepic = new SpannableString(yy_str);
                        spannablepic.setSpan(new ForegroundColorSpan(Color.WHITE),
                            3,
                            yy_str.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        spannablepic.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC),
                            3,
                            yy_str.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        spannablepic.setSpan(imageSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        chatMsg.setSpStr(spannablepic);
                    }
                    
                    chatMsg.setText("");
                } else if (Contact.POSMAP == Integer.valueOf(msgModel.getConType())) {
                    // 定位地点
                    chatMsg.setText(msgModel.getContent());
                    chatMsg.setFileName(msgModel.getFileName());
                }
                chatMsgs.add(chatMsg);
            }
        }
        return chatMsgs;
    }
    
    /**
     * 根据聊天记录的ID删除msg_model表中数据
     * 
     * @param id
     * 
     * @return
     */
    public void deleteMagModelById(int id) {
        msgDao.delete(id);
    }
    
    // 根据聊天记录的ID删除msg_model表中数据
    public void deleteMsgModelByUUID(String uuid) {
        msgDao.deleteByUUID(uuid);
    }
    
    /**
     * 根据聊天记录的ID查询msg_model表中数据
     * 
     * @param id
     * 
     * @return
     */
    public MsgModel getMsgModelById(int id) {
        return (MsgModel)msgDao.get(id);
    }
    
    /**
     * 根据聊天记录的UUID查询msg_model表中数据
     * 
     * @param id
     * 
     * @return
     */
    public MsgModel getMsgModelByUUID(String uuid) {
        return (MsgModel)msgDao.getByUUID(uuid);
    }
    
    public List<MsgModel> getAllMsgModel() {
        List<MsgModel> listMsgModel = new ArrayList<MsgModel>();
        String sql = "select * from msg_model";
        listMsgModel = msgDao.rawQuery(sql, null);
        return listMsgModel;
    }
    
    public List<IMList> getAllIMList() {
        List<IMList> listMsgModel = new ArrayList<IMList>();
        String sql = "select * from im_list";
        listMsgModel = imDaoImpl.rawQuery(sql, null);
        return listMsgModel;
    }
    
    public void delMsgModel(String groupId) {
    	String sql = "delete from msg_model where group_id='"+groupId+"'";
    	imDaoImpl.execSql(sql, null);
    }
    
}
